﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;
using System.Reflection;
using ZGL.Api.Data;
using ZGL.Api.Filters;
using ZGL.Api.Mapping;
using ZGL.Api.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddDbContext<DataContext>(options => 
  options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"), new MySqlServerVersion(new Version(5, 6, 51)))
);

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//配置Swagger身份验证输入（可选）
builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "请输入token,格式为 【Bearer JWT字符串】（注意中间必须有空格）",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    //添加安全要求
    options.AddSecurityRequirement(new OpenApiSecurityRequirement {
        {
            new OpenApiSecurityScheme{
                Reference =new OpenApiReference{
                    Type = ReferenceType.SecurityScheme,
                    Id ="Bearer"
                }
            },new string[]{ }
        }
    });
    var path = Path.Combine(AppContext.BaseDirectory, "ZGL.Api.xml"); // xml文档绝对路径,"API"为项目名
    options.IncludeXmlComments(path, true); // true : 设置控制器层注释
    options.OrderActionsBy(o => o.RelativePath); // 排序用的
    //设置对象类型参数默认值
    options.SchemaFilter<DefaultValueSchemaFilter>();
});



builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
    // 设置JSON返回日期格式
    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    // 统一设置API的日期格式
    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});
// 以下是autofac依赖注入
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
#region 注入Service程序集
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{   // 注入Service程序集
    string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
    builder.RegisterAssemblyTypes(Assembly.Load(assemblyName))
    .AsImplementedInterfaces()
    .InstancePerDependency();
});
#endregion

#region 注册Mappe
builder.Services.AddAutoMapper(typeof(MappingProfile));
#endregion

var app = builder.Build();
#region 注册错误返回中间件
// 注册错误返回中间件
app.UseMiddleware<ErrorHandlingMiddleware>();
#endregion
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run("http://*:5000");
